#include <opengl/application.h>
#include <iostream>

namespace opengl
{

Application* Application::_instance = nullptr;

//! @brief 单例模式获取实例化对象
//! @return Application* 
Application* Application::instance()
{
    if (Application::_instance == nullptr)
    {
        opengl::Window::init();
        Application::_instance = new Application();
    }
    return Application::_instance;
}

//! @brief 释放单例对象
void Application::free()
{
    delete Application::_instance;
    Application::_instance = nullptr;
    opengl::Window::terminate();
}

//! @brief 构造函数实现
Application::Application() : 
    _windows{}, _textures{}, _shaders{}
{
}

//! @brief 析构函数实现
Application::~Application() noexcept
{
    this->_currentWindow = nullptr;

    // 释放 opengl window 对象
    for (Window* window : this->_windows)
    {
        delete window;
    }

    // 释放 opnegl 纹理对象
    for (auto iter = this->_textures.begin(); iter != this->_textures.end(); ++iter)
    {
        iter->second->free();
        delete iter->second;
        iter->second = nullptr;
    }

    // 释放 opengl 着色器对象
    for (auto iter = this->_shaders.begin(); iter != this->_shaders.end(); ++iter)
    {
        iter->second->free();
        delete iter->second;
        iter->second = nullptr;
    }
}

//! @brief 激活纹理对象
void Application::activeTextures()
{
    for (auto iter = this->_textures.begin(); iter != this->_textures.end(); ++iter)
        iter->second->active();
}

}